<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_actions_AjaxSwitchPublicationStatusAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$docId = $this->getRequestParameter("docId");
        $docModel = $this->getRequestParameter("docModel");
		$lang = $this->getRequestParameter("docLang");
        $saveButton = $this->getRequestParameter("saveButton");
		$rows = $this->getFormValues("row");
        $nyroModal = $this->getRequestParameter("nyroModal");
		$nbRows = count($rows);
        $errors = array();

		if(!is_null($docId))
		{
            if($saveButton == 1 || is_null($docModel))
            {
                $docModel = "modules_backoffice/folder";
            }

            $document = $this->getDocumentProvider()->getByModelAndUniqueId($docModel, $docId, $lang);
            $this->addToModel("folder", $document);
		}

        //Change with the bullet on the list
        if(is_null($saveButton) && is_null($nyroModal))
        {
            $this->changeStatus($document);
            return 'itemStatusButton'.$document->getPublicationstatus();
        }
        elseif($saveButton == 1)
        {
            $uniqueRow = $this->getDocumentProvider()->getByUniqueId($rows[0], $lang);

            if($nyroModal == 1)
            {
                $docProvider = $this->getDocumentProvider();
                foreach($rows as $contentId)
                {
                    $content = $docProvider->getByModelAndUniqueId($uniqueRow->getModel(), $contentId, $lang);
                    $this->changeStatus($content);
                }

                $errors["status"] = "success";
            }

            $this->addToModel("uniqueRow", $uniqueRow);
            $this->addToModel("errors", $errors);            
            $this->addToModel("lang", $lang);
            $this->addToModel("rows", $rows);
            $this->addToModel("nbRows", $nbRows);
            $this->setView('success');
        }
	}	
	
    private function changeStatus($document)
    {
        /* @var $document f_document_BaseDocument */

		if($document->getPublicationstatus() == "PUBLISHED")
		{
		    $document->setPublicationstatus("DRAFT");
		}
		else if($document->getPublicationstatus() == "DRAFT")
		{
		    $document->setPublicationstatus("PUBLISHED");
		}

        $document->save(false);
    }
}